/**
 *
 *  @file ext-chart.js
 *
 *
 * @copyright 2010 CloudCanvas, Inc. All rights reserved
 * @copyright 2021 Optimistik SAS, Inc. All rights reserved
 * @license 
 *
 */

 const pathJT = 'path://M5,20 L5,5 L8,8 L5,2 L2,8 L5,5 L5.3,6 L5.3,20'

 const name = 'ext_echart'
 var option = {}
 const initOption = function(){
     option = {
         tooltip: {
           trigger: "axis",
         },
         legend: {
           show: false,
           top: 5,
           itemWidth: 15,
           formatter: function (name) {
             return name;
           },
           itemHeight: 15,
         },
         grid: {
           top:"3%",
           left: "8%",
           right: "4%",
           bottom: "3%",
           containLabel: true,
         },
         xAxis: {
           type: "category",
           boundaryGap: false,
           axisLine: {
             lineStyle: {
               color: "#3683f7", // 设置 x 轴线颜色
             },
           },
           axisLabel: {
             color: "#3683f7", // 设置 x 轴字体颜色
           },
         },
         yAxis: {
           name: "功率",
           type: "value",
           position: "left",
           axisTick: {
             inside: true,
             show: true,
           },
           axisLine: {
             show: true,
             lineStyle: {
               color: "#3683f7", // 设置 x 轴线颜色
             },
           },
           axisLabel: {
             formatter: "{value}MW",
             color: "#3683f7", // 设置 x 轴字体颜色
           },
         },
         series: [
           
         ],
       }
 }
 const loadExtensionTranslation = async function (svgEditor) {
     let translationModule
     const lang = svgEditor.configObj.pref('lang')
     try {
         translationModule = await import(`./locale/${lang}.js`)
     } catch (_error) {
         console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
         translationModule = await import('./locale/en.js')
     }
     svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
 }
 const initChart = function (container, option) {
     if (!option) {
         return;
     }
     $(container).empty()
     $(container).parent().attr("requiredFeatures", btoa(unescape(encodeURIComponent(JSON.stringify(option)))))
     var chart = echarts.init(container, "macarons", {
         renderer: 'svg'
     });
     chart.setOption(option);
     return chart
 }
 
 export default {
     name,
     async init() {
         const svgEditor = this
         const { svgCanvas } = svgEditor
         const { ChangeElementCommand } = svgCanvas.history
         const addToHistory = (cmd) => { svgCanvas.undoMgr.addCommandToHistory(cmd) }
         const { $id, $click, $qq, $ } = svgCanvas
         let selElems
         let started
         let newFO
         let foreignObject
         let p = {}
         let charts = new Map()
         await loadExtensionTranslation(svgEditor)
         /**
          *
          * @param {string} attr attribute to change
          * @param {string|Float} val new value
          * @returns {void}
          */
         const isGecko = navigator.userAgent.includes('Gecko/')
         const setAttrs = (elem, attrs) => {
             if (isGecko) {
                 Object.entries(attrs).forEach(([aname, val]) => {
                     elem.setAttribute(aname, val)
                 })
             } else {
                 Object.entries(attrs).forEach(([aname, val]) => {
                     const prop = elem[aname]
                     if (prop?.constructor === 'SVGLength') {
                         prop.baseVal.value = val
                     } else {
                         elem.setAttribute(aname, val)
                     }
                 })
             }
         }
 
 
         return {
             name: svgEditor.i18next.t(`${name}:name`),
             // The callback should be used to load the DOM with the appropriate UI items
             callback() {
                 // Add the button and its handler(s)
                 // Note: the star extension needs to be loaded before the polygon extension
                 const fbtitle = `${name}:title`
                 const titleStar = `${name}:buttons.0.title`
                 const titlePolygon = `${name}:buttons.1.title`
                 const buttonTemplate = `
                <se-button id="tool_echart" title="${titlePolygon}" src="echart.svg">
                </se-button>
            `
                 svgCanvas.insertChildAtIndex($qq('.shaps .itemWrap'), buttonTemplate, 20)
 
                 $click($id('tool_echart'), () => {
                     if (this.leftPanel.updateLeftPanel('tool_echart')) {
                         svgCanvas.setMode('echart')
                     }
                 })
             },
             mouseDown(opts) {
                 if (svgCanvas.getMode() === 'echart') {
                     started = true
                     //'x', 'y', 'r1', 'r2', 'angle', 'largeArcFlag', 'sweepFlag'
                     p.x = opts.start_x
                     p.y = opts.start_y
                     var svgId = svgCanvas.getNextId()
                     newFO = svgCanvas.addSVGElementsFromJson({
                         element: 'g',
                         attr: {
                             class: 'ems echart',
                             id: svgId,
                             'doc-type': 'echart'
                         }
                     })
 
                     foreignObject = svgCanvas.addSVGElementsFromJson({
                         element: 'foreignObject',
                         attr: {
                             x: p.x,
                             y: p.y,
                             width: 450,
                             height: 310,
                             class: 'foreignObject',
                             id: "foreignObject" + svgId,
                             'font-size': 12,
                             'fill': "yellow",
                             'text-anchor': 'middle',
                             'xml:space': 'preserve',
                             'stroke': 'none',
                             'opacity': 1,
                         }
                     })
                     newFO.append(foreignObject)
                     initOption()
                     var chart = initChart(document.getElementById(`foreignObject${svgId}`), option,true)
                     charts.set(`foreignObject${svgId}`, chart)
                     return {
                         started: true
                     }
                 }
                 return undefined
             },
             mouseMove(opts) {
                 var eles = svgCanvas.getSelectedElements()
                 if (svgCanvas.getMode() === 'resize') {
                     if (eles.length == 1 && eles[0].classList.contains("echart")) {
                         var chart = charts.get("foreignObject" + eles[0].id)
                         if (chart) {
                             chart.resize()
                         }
                         return {
                             started: true
                         }
                     }
                 }
                 return undefined
             },
             mouseUp() {
                 if (svgCanvas.getMode() === 'resize' || svgCanvas.getMode() === 'select') {
                     var eles = svgCanvas.getSelectedElements()
                     if (eles.length >= 1 && eles[0].classList.contains("echart")) {
                         var chart = charts.get("foreignObject" + eles[0].id)
                         if (chart) {
                             chart.resize()
                             return {
                                 started: false
                             }
                         }
                     }
                 }
                 if (svgCanvas.getMode() === 'echart') {
                     const keep = true
 
                     return {
                         keep,
                         element: newFO
                     }
                 }
                 return undefined
             },
             sourceChanged(opts) {
                 
                 let elem = opts.elems[0];
                 if (!elem) return;
                 let len = $(elem).find(".foreignObject").length;
                 if (elem.tagName === 'svg' && elem.id === 'svgcontent' && len) {
                     // Update svgContent (can change on import)
                     var svgContent = elem;
                     var foreignObjects = $(svgContent).find(".foreignObject")
                     Array.from(foreignObjects).forEach((elem, i) => {
                         if (charts.get(elem.id) != null) {
                             charts.get(elem.id).dispose()
                             charts.delete(elem.id)
                         }
                         $(elem).removeAttr("_echarts_instance_")
                         var state = $(elem).parent().attr("requiredFeatures")
                         if (state) {
                             option = JSON.parse(decodeURIComponent(escape(atob(state))))
                         }
                         var chart = initChart(document.getElementById(elem.id), option,true)
                         charts.set(elem.id, chart)
                     })
                 }
             },
             // updateechartold(opts) {
             //     if (opts.mode != "echart") {
             //         return
             //     }
             //     var eles = svgCanvas.getSelectedElements()
             //     var data = opts.data
             //     if (data.showTitle) {
             //         option.title.text = data.title
             //         option.title.textStyle.color = data.title_color
             //         option.title.textStyle.fontWeight = data?.fontSetValue?.cssstyle?.["font-weight"] || null
             //         option.title.textStyle.fontFamily = data?.fontSetValue?.cssstyle?.["fontfirst"] || null
             //         option.title.textStyle.fontSize = data?.fontSetValue?.cssstyle?.["font-size"] || null
             //         option.title.textStyle.fontStyle = data?.fontSetValue?.cssstyle?.["font-style"] || null
             //     }else{
             //         option.title.text = ""
             //     }
             //     option.grid.backgroundColor = data.zbq_color
             //     option.grid.borderColor = data.grid_color
             //     option.xAxis.splitLine = { show: true, lineStyle: { color: data.zb_color, width: 1, type: 'solid' } }
             //     option.xAxis.axisLine.lineStyle =  { color: data.zb_color, width: 1, type: 'solid'}
             //     if(data.tableData.length>0){
             //         option.grid.x = data.tableData.length*50
             //         option.yAxis = null
             //         option.yAxis = []
             //         data.tableData.forEach((row,index)=>{
             //             var yAxias = {
             //                 axisTick: { show: true,inside:true },
             //                 position:'left',
             //                 name:row.name,
             //                 offset:index*50,
             //                 max:row.max,
             //                 nameGap:25,
             //                 min:row.min,
             //                 splitNumber:row.num,
             //                 axisLine: {
             //                     show: true,
             //                     symbol: ['none', pathJT],
             //                     symbolOffset: 8,  
             //                     symbolSize: [35, 35],  
             //                     lineStyle:{ color: row.color, width: 1, type: 'solid' }
             //                 },
             //                 splitLine:{ show: true, lineStyle: { color: data.zb_color, width: 1, type: 'solid' } },
             //                 type: 'value'
             //             }
             //             option.yAxis.push(yAxias)
             //         })
             //     }
             //     if(data.lineSet.length>0){
             //         option.legend.data =[]
             //         option.series = []
             //         data.lineSet.forEach((row,index)=>{
             //             var add= index*10
             //             var rname = row.dname.split(":")[1]
             //             var serie = { 
             //                 symbol: "none",
             //                 name:rname,
             //                 yAxisIndex:row?.index|| 0,
             //                 // data: [1+add,2+add,3+add,4+add,5+add],
             //                 type: 'line',
             //                 smooth: true,
             //                 lineStyle:{color:row.qx_color}
             //               }
             //             option.legend.data.push({
             //                 name: serie.name,
             //                 textStyle: {
             //                     color: row.qx_color
             //                 }
             //             })
             //             option.series.push(serie)
             //         })
             //     }
             //     charts.get(eles[0].firstChild.id).setOption(option,true);
             //     $(eles[0]).attr("requiredFeatures", btoa(unescape(encodeURIComponent(JSON.stringify(option)))))
             //     $(eles[0]).attr("state", btoa(unescape(encodeURIComponent(JSON.stringify(data)))))
             // },
             updateechart(opts) {
                 if (opts.mode != "echart") {
                     return
                 }
                 var eles = svgCanvas.getSelectedElements();
                 var data = opts.data;
                 var data =opts.data.finallyObj;
                 var notFormdata = opts.data.saveobj;
 
                 if(notFormdata.yAxisData && notFormdata.yAxisData.length){
                     option.legend={
                         show:true,
                       }
                       option.tooltip={
                        trigger: "axis",
                      }
                      option.series=[];
                       notFormdata.yAxisData.forEach((res,index)=>{
                         option.series.push({
                             name:res.link_name,
                             data: [(index+1)*10, (index+1)*20, (index+1)*30],
                             type: 'line',
                             itemStyle:{
                                 color:res.color
                             }
                         })
                       })
                       
                       charts.get(eles[0].firstChild.id).setOption(option,true);
                 }
                 $(eles[0]).attr("requiredFeatures", btoa(unescape(encodeURIComponent(JSON.stringify(option)))))
                 $(eles[0]).attr("state", btoa(unescape(encodeURIComponent(JSON.stringify(data)))))
                 $(eles[0]).attr("notFormdata", btoa(unescape(encodeURIComponent(JSON.stringify(notFormdata)))))
                 svgEditor.layersPanel.populateObjects()
                //  addToHistory(new ChangeElementCommand(eles[0],{state:btoa(unescape(encodeURIComponent(JSON.stringify(data)))),requiredFeatures:btoa(unescape(encodeURIComponent(JSON.stringify(option)))),notFormdata:btoa(unescape(encodeURIComponent(JSON.stringify(notFormdata))))}))
             }
         }
     }
 }
 